<template>
  <view class="top">
    <!-- 显示日期范围 -->
    <text class="t1">{{ formattedDates }}</text>
    <text class="t1">{{ nights }} 晚</text>
    <view class="example-body">
      <uni-datetime-picker v-model="range" type="daterange" @maskClick="maskClick" />
    </view>
    <view class="top1">
      <text>{{ fxList.title }}</text>
      <text class="blue">￥{{ fxList.price }}元/晚</text>
    </view>
  </view>
  <view class="min">
    <view class="big">订房信息</view>
    <view class="min1">
      <text class="text">住客信息</text>
      <input class="uni-input" v-model="name" placeholder="请输入姓名" />
    </view>
    <view class="min2">
      <text class="text">手机号</text>
      <input class="uni-input" v-model="phone" type="number" placeholder="请输入手机号" />
    </view>
  </view>
  <view class="con">
    <text class="title">优惠券</text>
    <view class="coupons-list">
      <view class="coupon-item" v-for="(coupon, index) in coupons" :key="index">
        <checkbox-group @change="handleCouponChange">
          <label>
            <checkbox :value="coupon.name" :checked="selectedCoupon === coupon.name" />
            <text class="coupon-name">{{ coupon.name }}</text>
            <text class="discount">- ¥{{ coupon.price }}元</text>
          </label>
        </checkbox-group>
      </view>
    </view>
  </view>
  <view class="btm">
    <view class="price">￥{{ totalPrice }}元</view>
    <view>
      <button @click="pay()">确定支付</button>
    </view>
  </view>
 <!-- <view class="list">
    <view class="item" v-for="(item, index) in bookingList" :key="index">
      <text>订单号: {{ item.ddbh }}</text>
      <text>姓名: {{ item.name }}</text>
      <text>价格: {{ item.price }}元</text>
      <text>时间: {{ item.time }}</text>
      <text>房间名称: {{ item.jname }}</text>
    </view>
  </view> -->
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue';
import { onLoad } from '@dcloudio/uni-app';

const name = ref<string>('');
const phone = ref<string>('');
const selectedCoupon = ref<string>('');
const coupons = ref<any[]>([
  { id: 1, name: '优惠券A', price: 50 },
  { id: 2, name: '优惠券B', price: 30 },
]);

const handleCouponChange = (event) => {
	if(nights.value<=0){
		uni.showToast({
			title:'请选择要入住的日期和退房日期',
			icon:'error',
		})
		return;
	}
  const selectedValue = event.detail.value[0];
  if (selectedValue) {
    selectedCoupon.value = selectedValue;
  } else {
    selectedCoupon.value = '';
  }
};

const fxList = ref<any>({});
const loading = ref<boolean>(true);
const range = ref<string[]>([]);

const maskClick = (e) => {
  console.log('maskCheck事件:', e);
};

const pay = () => {

  if (phone.value && name.value && range.value.length) {
    // 生成随机订单号
    const code = generateOrderNumber();
    uni.request({
      url: `http://127.0.0.1:3000/ljy/addhshop`,
      method: 'POST',
      data: {
        ddbh: code,
		date:formattedDates.value,
        name: name.value,
		num:nights.value,
		imgurl:fxList.value.imgurl,
		fx:fxList.value.title,
        price: totalPrice.value,
        time: range.value.join(' - '),
        jname: fxList.value.hid.title
      },
      success(res) {
        console.log(res);
			// 清空输入框
			name.value = '';
			phone.value = '';
			range.value = [];
			
			uni.showToast({
			  title: '支付成功',
			  icon: 'success'
			});
			uni.navigateTo({
				url:'/pages/reserve1/reserve1'
			})
      },
      fail(err) {
        console.error('请求失败:', err);
        uni.showToast({
          title: '支付失败',
          icon: 'error'
        });
      }
    });
  } else {
    uni.showToast({
      title: '请填写完整信息',
      icon: 'error'
    });
  }
};

const nights = computed(() => {
  return calculateNights(range.value);
});

const formattedDates = computed(() => {
  return formatDates(range.value);
});

const totalPrice = computed(() => {
  const basePrice = fxList.value.price * nights.value;
  if (selectedCoupon.value) {
    const selectedCouponPrice = coupons.value.find(
      (c) => c.name === selectedCoupon.value
    ).price;
    return basePrice - selectedCouponPrice;
  }
  return basePrice;
});

const calculateNights = (dateRange: string[]) => {
  if (!dateRange.length) return 0;
  const [startDate, endDate] = dateRange.map((date) => new Date(date));
  return Math.max(0, Math.ceil((endDate - startDate) / (1000 * 60 * 60 * 24)));
};

const formatDates = (dateRange: string[]) => {
  if (!dateRange.length) return '';
  const [startDate, endDate] = dateRange.map((date) => new Date(date));
  return `${startDate.getMonth() + 1}月${startDate.getDate()}日 - ${endDate.getMonth() + 1}月${endDate.getDate()}日`;
};

const generateOrderNumber = () => {
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let orderNumber = '';
  for (let i = 0; i < 10; i++) {
    orderNumber += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  return orderNumber;
};

onMounted(() => {
  watch(range, () => {
    console.log('range changed', range.value);
  });
});

onLoad((options) => {
  if (options.item) {
    try {
      const itemStr = decodeURIComponent(options.item);
      fxList.value = JSON.parse(itemStr);
      loading.value = false;
    } catch (error) {
      console.error('解析数据失败:', error);
    }
  }
});
</script>

<style lang="scss">
.top {
  padding: 10rpx;
  margin-bottom: 20rpx;
  .t1 {
    font-size: 40rpx;
    padding-right: 20rpx;
  }
  .top1 {
    .blue {
      color: blue;
      padding-left: 20rpx;
    }
  }
}
.min {
  padding: 10rpx;
  .big {
    font-size: 38rpx;
    font-weight: 500;
    padding-bottom: 20rpx;
  }
  .min1, .min2 {
    display: flex;
    padding-bottom: 15rpx;
    padding-left: 15rpx;
    .uni-input {
      padding-left: 30rpx;
    }
  }
}
.con {
  padding: 20rpx;
  height: 100rpx;
  .coupon-item {
    padding-top: 30rpx;
    padding-left: 20rpx;
    display: flex;
    .discount {
      padding-left: 380rpx;
      color: red;
    }
  }
}
.btm {
  position: fixed;
  bottom: 30rpx;
  width: 100%;
  padding-top: 100rpx;
  display: flex;
  width: 100%;
  height: 100rpx;
  line-height: 100rpx;
  align-items: center;
  .price {
    text-align: center;
    color: blue;
    height: 100rpx;
    background-color: whitesmoke;
  }
  view {
    width: 50%;
    button {
      background-color: blue;
      color: white;
    }
  }
}
.list {
  margin-top: 20rpx;
  .item {
    padding: 20rpx;
    border-bottom: 1px solid #ccc;
  }
}
</style>